{% extends "index.html" %}
{% block css %}
    <style>
        .font-20{
            font-size: 20px;
        }
        input{
            background-color: aquamarine;
        }


        .main{
            position: relative;
            height: 1000px;
            background-color: antiquewhite;
            font-size: 30px;
        }
        .left{
            position: absolute;
            left: 0;
            width: 30%;
            height: 100%;
            background-color: aquamarine;
            padding-left: 20px;
        }
        .right{
            position: absolute;
            right: 0;
            width: 70%;
            height: 100%;
            background-color: #6b9d8c;
            padding: 20px;
        }
        .lab{
            border: 1px solid black;
            font-size: 25px;
        }
        .lab-y{
            background-color: green;
        }
        .lab-q{
            background-color: orange;
        }
        .y-item{
            margin-top: 10px;
        }
        .y-item:hover{
            background-color: blueviolet;
        }
        .active{
            background-color: blueviolet;
        }
        .chat-msg{
            width: 100%;
            height: 800px;
            border: 2px solid black;
        }
        .txt-right{
            text-align: right;
        }
        textarea{
            background-color: #6b9d8c;
        }
        .div-bottom{
            position: absolute;
            bottom: 5px;
            height: 200px;
            overflow: auto;
        }
        #msg_main{
            height: 800px;
            overflow: auto;
            padding: 10px;
        }
    </style>
{% endblock %}

{% block body %}
    <h3>你的ID：{{ uid }}  你的名字：{{ username }} <span id="tag"></span> </h3>
    <div class="main">

        <div class="left">
            <p>
                <span>好友列表</span>
                <span class="font-20 point" onclick="add_user(1)">添加好友</span>
                <span class="font-20 point" onclick="add_user(2)">添加群</span>
                <input class="font-20" type="text" placeholder="好友ID或者群名字" id="add_obj">
                <span class="point" onclick="reful()">刷新</span>
            </p>
            <div style="overflow: auto">
                {% for item in obj_list %}
                    <div class="y-item point user_{{ item.type }}_{{ item.obj_id }}" onclick="go_chat({{ item.obj_id }},{{ item.type }},'{{ item.obj_name }}')">
                        {% if item.type == 1 %}
                            <span class="lab lab-y">友</span>
                        {% else %}
                            <span class="lab lab-q">群</span>
                        {% endif %}
                        <span>{{ item.obj_name }}</span>
                        {% if item.last_msg_txt %}
                            <span style="color: gray;font-size: 20px">{{ item.send }}:{{ item.last_msg_txt }}</span>
                        {% endif %}
                        <span id="new_msg_{{ item.type }}_{{ item.obj_id }}" style="font-size: 14px;color: red;display: none;"> 新消息</span>
                    </div>
                {% endfor %}
            </div>
            <div class="div-bottom" style="font-size: 20px">
                <p>所有用户信息</p>
                {% for i in all_user %}
                    <span>{{ i.id }}-{{ i.name }}|</span>
                {% endfor %}
                <p>所有群信息</p>
                {% for i in all_qun %}
                    <span>{{i}}|</span>
                {% endfor %}
            </div>
        </div>
        <div class="right">
            <div class="chat-msg" id="msg_main">

            </div>
            <div style="margin-top: 10px">
                <textarea name="" id="send_txt" cols="50" rows="3"></textarea>
                <button onclick="send_msg()">发送</button>
            </div>
        </div>
    </div>
{% endblock %}

{% block base_js %}
    <script>
        var socket = new WebSocket(`ws://192.168.1.99:8000/init/{{ uid }}/B256954N5/`);
        var tag = $('#tag')
        var cur_obj_id = ''
        var cur_obj_name=''
        var is_qun = 0
        console.log('建立链接')
        // 创建好websocket连接成功后自动触发（服务端执行self.accept()后）
        socket.onopen = function (event) {
            tag.text('[连接成功！]');
        };

        // 创建连接失败后自动触发
        socket.onerror = function (event) {
            tag.text('[连接失败！]');
        };
        // 当websocket接收到服务器发来的消息时会自动触发
        socket.onmessage = function (event) {
            console.log('收到消息',event)
            let d = JSON.parse(event.data);

            if(d.type == 3){    // 文本消息
                if(cur_obj_id==d.from_id&d.is_qun==1||cur_obj_id==d.to_id&d.is_qun==2 || d.from=='系统'){  // 在当前聊天
                    let html = d.from_id=='{{ uid }}'? `<p class="txt-right"><span>${d.from}：</span>${d.txt}</p>`:`<p><span>${d.from}：</span>${d.txt}</p>`
                    $('#msg_main').append(html)
                }else{  // 不在当前聊天
                    let t = d.zdy.type
                    if(d.is_qun==1){
                        $(`#new_msg_${t}_${d.from_id}`).css('display','inline')
                    }else{
                        $(`#new_msg_${t}_${d.to_id}`).css('display','inline')

                    }
                }

            }else if(d.type == 1){ // 添加好友
                let msg = `${d.from}添加了你为好友`
                alert(msg)
                location.reload()
            }
        };

        // 当服务端主动断开客户端时自动触发（服务端执行self.close()后）
        socket.onclose = function (event) {
            tag.text('[连接断开！]');
        };
    </script>
    <script>
        function reful(){
            location.reload()
        }
        function add_user(type){
            let txt = $('#add_obj').val()
            let uri = `/add_obj/?uid={{ uid }}&obj=${txt}&type=${type}`
            $.get(uri).then((res)=>{
                let data = JSON.parse(res)
                if(data.status==1){
                    alert('添加成功')
                    location.reload()
                }else{
                    alert('添加失败，原因：'+data.error)
                }
            })
        }
        function send_msg(){
            let txt = $('#send_txt').val()
            let html = `<p class="txt-right"><span>{{ username }}：</span>${txt}</p>`
            $('#msg_main').append(html)
            let text = {
                "from_id":{{ uid }},
                "from":'{{ username }}',
                "to_id":cur_obj_id,
                "to":cur_obj_name,
                "type":3, // 1 添加好友 2 添加群 3 文字消息 4 语音消息 5 图片消息 6 链接消息 100系统消息
                "txt":txt,
                "zdy":{},
                "is_qun":is_qun
            }
            socket.send(JSON.stringify(text));   // 客户端给服务端发数据
            $('#send_txt').val('')
        }
        function go_chat(obj_id,type,obj_name){
            cur_obj_id = obj_id
            cur_obj_name = obj_name
            is_qun = Number(type)
            let uri = `/get_msg/?uid={{ uid }}&obj_id=${obj_id}&type=${type}`
            $.get(uri).then((res)=>{
                let data = JSON.parse(res)
                let html = ""
                for(let i=0;i<data.length;i++){
                    let item = data[i]
                    if(item.is_self==1){
                        html+=`<p class="txt-right"><span>${item.msg_from}：</span>${item.text}</p>`
                    }else{
                        html+=`<p><span>${item.msg_from}：</span>${item.text}</p>`
                    }
                }
                $('#msg_main').html(html)
            })
            $('.y-item').removeClass('active')
            $(`#new_msg_${type}_${obj_id}`).css('display','none')
            $('.user_'+type+'_'+obj_id).addClass('active')

        }
    </script>
{% endblock %}

